from pathlib import Path
from PIL import Image
from PIL.Image import UnidentifiedImageError

def load_images_from_project_root():
    current_dir = Path(__file__).parent
    project_root = current_dir.parent.parent
    image_dir = project_root / "images"
    if not image_dir.exists():
        raise FileNotFoundError(f"图片目录不存在: {image_dir}")
    if not image_dir.is_dir():
        raise NotADirectoryError(f"{image_dir} 不是目录")
    IMAGE_EXTENSIONS = ["*.jpg", "*.jpeg", "*.png", "*.bmp", "*.gif", "*.tiff"]
    image_paths = []
    for ext in IMAGE_EXTENSIONS:
        image_paths.extend(image_dir.glob(ext))
    images = {}
    for img_path in image_paths:
        try:
            if img_path.is_file():
                images[img_path.name] = Image.open(img_path)
        except UnidentifiedImageError as e:
            print(f"无法识别的图片格式: {img_path.name} - {str(e)}")
        except Exception as e:
            print(f"加载失败: {img_path.name} - {str(e)}")
    return images
if __name__ == "__main__":
    try:
        img_collection = load_images_from_project_root()
        print(f"成功加载 {len(img_collection)} 张图片")
        if img_collection:
            first_image = next(iter(img_collection))
            print(f"第一张图片: {first_image}")
            img = img_collection[first_image]
            print(f"尺寸: {img.size}, 模式: {img.mode}")
    except Exception as e:
        print(f"发生错误: {str(e)}")
